<template>
  <div class="contest-detail-container">
    <div class="back-link">
      <el-button 
        link 
        type="primary"
        @click="goBack"
        :icon="ArrowLeft"
      >
        返回竞赛列表
      </el-button>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <div v-else-if="!contestDetail" class="not-found-container">
      <el-empty description="未找到竞赛信息" />
    </div>

    <div v-else class="contest-content">
      <!-- 竞赛基本信息卡片 -->
      <el-card class="detail-card" shadow="hover">
        <div class="contest-header">
          <div class="title-status">
            <h1 class="contest-title">{{ contestDetail.title }}</h1>
            <el-tag
              class="contest-status"
              :type="getStatusType(contestDetail.status)"
              :effect="getStatusEffect(contestDetail.status)"
              round
            >
              {{ getStatusText(contestDetail.status) }}
            </el-tag>
          </div>
          
          <div class="creator-info">
            <span>发起人: {{ contestDetail.creatorName || '未知' }}</span>
          </div>
        </div>

        <div class="contest-cover">
          <el-image
            :src="contestDetail.coverImage"
            fit="cover"
            class="cover-image"
          >
            <template #error>
              <div class="image-placeholder">
                <el-icon size="40"><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </div>

        <div class="contest-info">
          <div class="info-item">
            <el-icon><Calendar /></el-icon>
            <span>开始时间: {{ formatDateTime(contestDetail.startTime) }}</span>
          </div>
          <div class="info-item">
            <el-icon><Timer /></el-icon>
            <span>结束时间: {{ formatDateTime(contestDetail.endTime) }}</span>
          </div>
          <div class="info-item">
            <el-icon><User /></el-icon>
            <span>当前参与人数: {{ contestDetail.currentParticipants }} 人</span>
          </div>
          <div class="info-item" v-if="contestDetail.participantLimit">
            <el-icon><UserFilled /></el-icon>
            <span>人数限制: {{ contestDetail.participantLimit }} 人</span>
          </div>
          <div class="info-item">
            <el-icon><Medal /></el-icon>
            <span>颁发证书: {{ contestDetail.certificateEnabled ? `是 (前 ${contestDetail.certificateCount} 名)` : '否' }}</span>
          </div>
        </div>

        <el-divider />

        <div class="contest-description">
          <h3>竞赛描述</h3>
          <div class="description-content">{{ contestDetail.description || '暂无描述' }}</div>
        </div>

        <div class="contest-actions">
          <!-- 参加竞赛按钮：总是显示，但在前十分钟内置灰 -->
          <el-button 
            v-if="!isUserJoined" 
            type="primary" 
            @click="handleJoin" 
            :disabled="isWithinTenMinutes">
            {{ getJoinButtonText() }}
          </el-button>
          
          <!-- 进入实时答题按钮：总是显示 -->
          <el-button 
            v-if="isUserJoined" 
            type="success" 
            @click="showRulesDialog"
            :disabled="!canEnterLiveRoom && !canEnterWaitingRoom">
            进入实时答题
            <template v-if="countdownText">
              <br><small>({{ countdownText }})</small>
            </template>
          </el-button>
          
          <el-button v-if="isUserJoined && contestDetail.status === 2" type="primary" @click="viewRanking">查看排名</el-button>
          <el-button type="default" @click="goBack">返回</el-button>
        </div>
      </el-card>

      <!-- 评论区卡片 -->
      <el-card class="comment-card" shadow="hover">
        <template #header>
          <div class="comment-header">
            <h3>评论区</h3>
            <span>共 {{ comments.length }} 条评论</span>
          </div>
        </template>

        <!-- 添加评论 -->
        <div class="comment-input">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
            maxlength="500"
            show-word-limit
            resize="none"
          />
          <div class="input-actions">
            <el-button type="primary" round :disabled="!commentContent.trim()" @click="addComment">
              发表评论
            </el-button>
          </div>
        </div>

        <!-- 评论列表 -->
        <div v-if="commentsLoading" class="comments-loading">
          <el-skeleton :rows="3" animated />
        </div>
        
        <div v-else-if="comments.length === 0" class="comments-empty">
          <el-empty description="暂无评论，来发表第一条评论吧！" />
        </div>
        
        <div v-else class="comments-list">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-user">
              <el-avatar :size="40" :src="comment.userAvatar">
                {{ comment.nickname ? comment.nickname.substring(0, 1) : 'U' }}
              </el-avatar>
              <div class="user-info">
                <div class="user-name">{{ comment.nickname || '未知用户' }}</div>
                <div class="comment-time">{{ formatDateTime(comment.createTime) }}</div>
              </div>
            </div>
            
            <div class="comment-content">{{ comment.content }}</div>
            
            <div class="comment-actions">
              <el-button type="text" @click="toggleReply(comment.id)">
                {{ showReplyForm === comment.id ? '取消回复' : '回复' }}
              </el-button>
              <el-button type="text" :icon="ThumbUp" @click="likeComment(comment.id)">
                  <el-icon><Pointer /></el-icon>
                <span>{{ comment.likeCount || 0 }}</span>
              </el-button>
            </div>
            
            <!-- 回复表单 -->
            <div v-if="showReplyForm === comment.id" class="reply-form">
              <el-input
                v-model="replyContent"
                type="textarea"
                :rows="2"
                placeholder="回复内容..."
                maxlength="300"
                show-word-limit
                resize="none"
              />
              <div class="reply-actions">
                <el-button size="small" @click="toggleReply(0)">取消</el-button>
                <el-button 
                  type="primary" 
                  size="small" 
                  :disabled="!replyContent.trim()" 
                  @click="submitReply(comment.id)"
                >
                  提交回复
                </el-button>
              </div>
            </div>
            
            <!-- 回复列表 -->
            <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
              <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                <div class="reply-user">
                  <el-avatar :size="30" :src="reply.userAvatar">
                    {{ reply.nickname ? reply.nickname.substring(0, 1) : 'U' }}
                  </el-avatar>
                  <div class="user-info">
                    <div class="user-name">{{ reply.nickname || '未知用户' }}</div>
                    <div class="reply-time">{{ formatDateTime(reply.createTime) }}</div>
                  </div>
                </div>
                <div class="reply-content">{{ reply.content }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 评论分页 -->
        <div v-if="comments.length > 0" class="comment-pagination">
          <el-pagination
            v-model:current-page="commentPage"
            v-model:page-size="commentPageSize"
            :page-sizes="[5, 10, 20]"
            layout="sizes, prev, pager, next"
            :total="commentTotal"
            @size-change="handleCommentSizeChange"
            @current-change="handleCommentPageChange"
            background
            hide-on-single-page
          />
        </div>
      </el-card>

      <!-- 规则弹窗 -->
      <el-dialog
        v-model="rulesDialogVisible"
        title="竞赛规则及公平公约"
        width="600px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
      >
        <div class="rules-content">
          <h3>竞赛规则</h3>
          <p>1. 请独立完成所有题目，不得抄袭或与他人协作。</p>
          <p>2. 每道题目有固定的答题时间限制。</p>
          <p>3. 所有参赛者同时答题，首个答对者得分更高。</p>
          <p>4. 禁止使用外部工具或资料辅助答题。</p>
          
          <h3>公平公约</h3>
          <p>1. 我承诺遵守竞赛规则，独立思考，不作弊。</p>
          <p>2. 我理解违规行为将导致成绩无效。</p>
          <p>3. 我将尊重其他参赛者，遵守比赛秩序。</p>
          <p>4. 我将积极参与，展现自己的真实水平。</p>
        </div>
        <div class="countdown-timer">
          <span>{{ remainingTime }}秒后可进入</span>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeRulesDialog">取消</el-button>
            <el-button type="primary" :disabled="remainingTime > 0" @click="proceedToContest">
              我已阅读并同意以上规则
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  ref,
  computed,
  onMounted,
  onUnmounted
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getContestDetail, 
  getContestComments, 
  addComment, 
  replyComment, 
  likeComment,
  checkUserJoined,
  joinContest
} from '@/api/contest'
import { 
  Calendar, 
  Timer, 
  User, 
  UserFilled, 
  Medal, 
  Picture, 
  ThumbUp, 
  ArrowLeft 
} from '@element-plus/icons-vue'

export default {
  name: 'ContestDetail',
  components: {
    Calendar,
    Timer,
    User,
    UserFilled,
    Medal,
    Picture,
    ThumbUp,
    ArrowLeft
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    // 从路由参数获取竞赛ID
    const contestId = ref(route.params.id)
    
    // 竞赛详情
    const contestDetail = ref(null)
    const loading = ref(true)
    
    // 检查用户是否已登录
    const isLogin = ref(!!localStorage.getItem('token'))
    
    // 是否已参与竞赛
    const isUserJoined = ref(false)
    
    // 是否可以进入实时答题室
    const canEnterLiveRoom = ref(false)
    const timeCheckInterval = ref(null)
    const comments = ref([])
    const commentsLoading = ref(false)
    const commentContent = ref('')
    const replyContent = ref('')
    const showReplyForm = ref(0)
    const commentPage = ref(1)
    const commentPageSize = ref(10)
    const commentTotal = ref(0)
    const currentUser = ref(null)
    const isLiveContestMode = ref(false)
    const rulesDialogVisible = ref(false)
    const remainingTime = ref(0)
    const countdownText = ref('')

    // 获取当前用户信息
    const getCurrentUser = () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        currentUser.value = JSON.parse(userInfoStr)
      } else {
        ElMessage.warning('请先登录后再评论')
      }
      return currentUser.value
    }

    // 获取竞赛详情
    const fetchContestDetail = async () => {
      loading.value = true
      try {
        const res = await getContestDetail(contestId.value)
        if (res.code === 200) {
          contestDetail.value = res.data
          // 检查当前登录用户是否已参与竞赛
          if (isLogin.value) {
            checkUserJoinedStatus()
          }
          checkCanEnterLiveRoom()
          setupCountdown() // 设置倒计时
          
          // 如果竞赛即将开始（24小时内），设置定时器检查状态
          const now = new Date()
          const startTime = new Date(contestDetail.value.startTime)
          const hoursDiff = (startTime - now) / (1000 * 60 * 60) // 转换为小时
          
          // 如果距离开始不足24小时，设置更频繁的检查
          if (hoursDiff <= 24 && hoursDiff > 0) {
            // 清除之前的定时器
            if (timeCheckInterval.value) {
              clearInterval(timeCheckInterval.value)
            }
            
            // 根据距离开始时间设置不同的检查频率
            let checkInterval = 60000 // 默认1分钟检查一次
            if (hoursDiff <= 1) { // 小于1小时
              checkInterval = 30000 // 30秒检查一次
            }
            if (hoursDiff <= 0.1) { // 小于6分钟
              checkInterval = 10000 // 10秒检查一次
            }
            
            timeCheckInterval.value = setInterval(() => {
              // 重新获取竞赛详情
              refreshContestDetail()
            }, checkInterval)
          }
        } else {
          ElMessage.error(res.message || '获取竞赛详情失败')
        }
      } catch (error) {
        console.error(error)
        ElMessage.error('获取竞赛详情失败')
      } finally {
        loading.value = false
      }
    }
    
    // 刷新竞赛详情（不显示加载状态）
    const refreshContestDetail = async () => {
      try {
        const res = await getContestDetail(contestId.value)
        if (res.code === 200) {
          contestDetail.value = res.data
          // 检查状态
          if (isLogin.value) {
            checkUserJoinedStatus()
          }
          checkCanEnterLiveRoom()
          
          // 输出当前状态
          if (contestDetail.value) {
            const now = new Date();
            const startTime = new Date(contestDetail.value.startTime);
            const timeDiff = (startTime - now) / (1000 * 60); // 转换为分钟
            console.log(`[状态更新] 竞赛状态: ${getStatusText(contestDetail.value.status)}, 距离开始: ${timeDiff.toFixed(2)} 分钟, 是否已参与: ${isUserJoined.value}, 可进入等待室: ${canEnterWaitingRoom.value}, 可进入实时答题: ${canEnterLiveRoom.value}`);
          }
        }
      } catch (error) {
        console.error('刷新竞赛详情失败:', error)
      }
    }

    // 检查用户是否已参与竞赛
    const checkUserJoinedStatus = async () => {
      try {
        if (!isLogin.value) {
          isUserJoined.value = false
          return
        }
        
        const res = await checkUserJoined(contestId.value)
        if (res.code === 200) {
          isUserJoined.value = res.data
        }
      } catch (error) {
        console.error('检查参与状态失败:', error)
      }
    }

    // 获取评论列表
    const fetchComments = async () => {
      commentsLoading.value = true
      try {
        const params = {
          page: commentPage.value,
          size: commentPageSize.value
        }
        const res = await getContestComments(contestId.value, params)
        comments.value = res.data.records
        commentTotal.value = res.data.total
      } catch (error) {
        ElMessage.error('获取评论失败')
        console.error(error)
      } finally {
        commentsLoading.value = false
      }
    }

    // 添加评论
    const addNewComment = async () => {
      if (!commentContent.value.trim()) {
        ElMessage.warning('评论内容不能为空')
        return
      }
      
      // 检查用户是否登录
      const user = getCurrentUser()
      if (!user || !user.id) {
        ElMessage.warning('请先登录后再评论')
        return
      }
      
      try {
        await addComment(contestId.value, user.id, {
          content: commentContent.value
        })
        ElMessage.success('评论成功')
        commentContent.value = ''
        fetchComments()
      } catch (error) {
        ElMessage.error('发表评论失败')
        console.error(error)
      }
    }

    // 提交回复
    const submitReply = async (commentId) => {
      if (!replyContent.value.trim()) {
        ElMessage.warning('回复内容不能为空')
        return
      }
      
      // 检查用户是否登录
      const user = getCurrentUser()
      if (!user || !user.id) {
        ElMessage.warning('请先登录后再回复')
        return
      }
      
      try {
        await replyComment(contestId.value, commentId, user.id, {
          content: replyContent.value
        })
        ElMessage.success('回复成功')
        replyContent.value = ''
        showReplyForm.value = 0
        fetchComments()
      } catch (error) {
        ElMessage.error('回复失败')
        console.error(error)
      }
    }

    // 点赞评论
    const handleLikeComment = async (commentId) => {
      try {
        await likeComment(commentId)
        // 更新本地数据
        const index = comments.value.findIndex(c => c.id === commentId)
        if (index !== -1) {
          comments.value[index].likeCount = (comments.value[index].likeCount || 0) + 1
        }
        ElMessage.success('点赞成功')
      } catch (error) {
        ElMessage.error('点赞失败')
        console.error(error)
      }
    }

    // 切换回复表单显示
    const toggleReply = (commentId) => {
      showReplyForm.value = showReplyForm.value === commentId ? 0 : commentId
      if (showReplyForm.value === 0) {
        replyContent.value = ''
      }
    }

    // 处理评论分页大小变化
    const handleCommentSizeChange = (size) => {
      commentPageSize.value = size
      commentPage.value = 1
      fetchComments()
    }

    // 处理评论页码变化
    const handleCommentPageChange = (page) => {
      commentPage.value = page
      fetchComments()
    }

    // 处理参与竞赛按钮点击
    const handleJoin = () => {
      // 检查用户是否已登录
      if (!isLogin.value) {
        ElMessage.warning('请先登录')
        router.push('/login')
        return
      }
      
      // 检查竞赛状态
      if (!canJoinContest.value) {
        return
      }

      ElMessageBox.confirm(
        '确定要参与此竞赛吗？',
        '参与确认',
        {
          confirmButtonText: '确定参与',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(async () => {
        try {
          const res = await joinContest(contestId.value)
          if (res.code === 200) {
            ElMessage.success('参与成功，竞赛开始时将收到通知')
            
            // 更新状态
            isUserJoined.value = true
            
            // 更新参与人数
            if (contestDetail.value) {
              contestDetail.value.participants = (contestDetail.value.participants || 0) + 1
            }
            
            // 检查是否可以进入房间
            checkCanEnterLiveRoom()
          } else {
            ElMessage.error(res.message || '参与失败')
          }
        } catch (error) {
          console.error('参与竞赛失败:', error)
          ElMessage.error('参与失败，请稍后重试')
        }
      }).catch(() => {
        // 用户取消参与，不做任何操作
      })
    }

    // 返回上一页
    const goBack = () => {
      router.push('/contest/list')
    }

    // 查看排名
    const viewRanking = () => {
      router.push(`/contest/ranking/${contestId.value}`)
    }

    // 进入实时答题
    const enterLiveContest = () => {
      router.push(`/contest/realtime/${contestId.value}`)
    }

    // 计算是否可以参与竞赛
    const canJoinContest = computed(() => {
      if (!contestDetail.value) return false
      
      // 检查竞赛状态是否为"已通过"
      if (contestDetail.value.status !== 1) return false
      
      // 检查是否已满员
      if (contestDetail.value.participantLimit && 
          contestDetail.value.currentParticipants >= contestDetail.value.participantLimit) {
        return false
      }
      
      // 检查是否距离比赛开始不足十分钟
      if (contestDetail.value.startTime) {
        const now = new Date()
        const startTime = new Date(contestDetail.value.startTime)
        const timeDiff = (startTime - now) / (1000 * 60) // 转换为分钟
        
        // 如果距离开始不足10分钟，不允许加入
        if (timeDiff < 10 && timeDiff >= 0) {
          return false
        }
      }
      
      return true
    })

    // 获取参与按钮文本
    const getJoinButtonText = () => {
      if (!contestDetail.value) return ''
      
      // 若已满员
      if (contestDetail.value.participantLimit && 
          contestDetail.value.currentParticipants >= contestDetail.value.participantLimit) {
        return '名额已满'
      }
      
      // 检查是否距离比赛开始不足十分钟
      if (contestDetail.value.startTime) {
        const now = new Date()
        const startTime = new Date(contestDetail.value.startTime)
        const timeDiff = (startTime - now) / (1000 * 60) // 转换为分钟
        
        // 如果距离开始不足10分钟，显示提示
        if (timeDiff < 10 && timeDiff >= 0) {
          return '开赛前10分钟禁止加入'
        }
      }
      
      // 若状态不为"已通过"
      if (contestDetail.value.status !== 1) {
        switch (contestDetail.value.status) {
          case 0: return '竞赛待审核'
          case 2: return '竞赛已拒绝'
          case 3: return '竞赛已取消'
          case 4: return '竞赛已结束'
          default: return '无法参与'
        }
      }
      
      return '立即参与'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '待审核'
        case 1: return '进行中'
        case 2: return '已拒绝'
        case 3: return '已取消'
        case 4: return '已结束'
        default: return '未知状态'
      }
    }

    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case 0: return 'warning'
        case 1: return 'success'
        case 2: return 'danger'
        case 3: return 'info'
        case 4: return 'primary'
        default: return 'info'
      }
    }

    // 获取状态效果
    const getStatusEffect = (status) => {
      return status === 1 ? 'light' : 'plain'
    }

    // 格式化日期时间
    const formatDateTime = (dateString) => {
      if (!dateString) return '未设置'
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }

    // 生命周期钩子
    onMounted(() => {
      fetchContestDetail()
      fetchComments()
    })
    
    // 组件销毁时清除定时器
    onUnmounted(() => {
      if (timeCheckInterval.value) {
        clearInterval(timeCheckInterval.value)
        timeCheckInterval.value = null
      }
      
      // 清除所有其他可能存在的定时器
      if (window.countdownTimer) {
        clearInterval(window.countdownTimer)
        window.countdownTimer = null
      }
    })

    // 计算是否可以进入等待室（比赛前5分钟）
    const canEnterWaitingRoom = computed(() => {
      if (!contestDetail.value || !isUserJoined.value) return false;
      
      if (contestDetail.value.status !== 1) return false;
      
      // 计算距离比赛开始的时间（分钟）
      const now = new Date();
      const startTime = new Date(contestDetail.value.startTime);
      const timeDiff = (startTime - now) / (1000 * 60); // 转换为分钟
      
      // 如果距离开始不足5分钟且大于0（未开始），允许进入等待室
      const canEnter = timeDiff <= 5 && timeDiff > 0;
      
      if (canEnter) {
        console.log(`距离比赛开始还有 ${timeDiff.toFixed(2)} 分钟，可以进入等待室`);
      }
      
      return canEnter;
    });

    // 检查是否可以进入实时答题房间
    const checkCanEnterLiveRoom = () => {
      if (!contestDetail.value || !isUserJoined.value) {
        canEnterLiveRoom.value = false;
        return;
      }
      
      // 检查竞赛状态是否为"进行中"
      if (contestDetail.value.status === 1) {
        // 检查当前是否在竞赛时间范围内
        const now = new Date();
        const startTime = new Date(contestDetail.value.startTime);
        const endTime = contestDetail.value.endTime ? new Date(contestDetail.value.endTime) : null;
        
        if (now >= startTime && (!endTime || now <= endTime)) {
          canEnterLiveRoom.value = true;
          return;
        }
      }
      
      canEnterLiveRoom.value = false;
    };

    // 显示规则弹窗
    const showRulesDialog = () => {
      rulesDialogVisible.value = true
      remainingTime.value = 10 // 强制用户阅读10秒
      
      // 启动倒计时
      const timer = setInterval(() => {
        remainingTime.value--
        if (remainingTime.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }

    // 关闭规则弹窗
    const closeRulesDialog = () => {
      rulesDialogVisible.value = false
    }
    //
    // // 继续进入竞赛
    // const proceedToContest = () => {
    //   rulesDialogVisible.value = false
    //   enterLiveContest()
    // }

    // 计算是否距离比赛开始不足十分钟
    const isWithinTenMinutes = computed(() => {
      if (!contestDetail.value) return false
      
      const now = new Date()
      const startTime = new Date(contestDetail.value.startTime)
      const timeDiff = (startTime - now) / (1000 * 60) // 转换为分钟
      
      return timeDiff < 10 && timeDiff >= 0
    })
    
    // 计算倒计时文本
    const updateCountdownText = () => {
      if (!contestDetail.value) return
      
      const now = new Date()
      const startTime = new Date(contestDetail.value.startTime)
      const timeDiff = startTime - now // 毫秒差值
      
      if (timeDiff <= 0) {
        // 竞赛已开始
        if (canEnterLiveRoom.value) {
          countdownText.value = '已开始'
        } else {
          countdownText.value = ''
        }
        return
      }
      
      // 计算天、时、分、秒
      const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000)
      
      // 格式化显示
      if (days > 0) {
        countdownText.value = `还有${days}天${hours}小时`
      } else if (hours > 0) {
        countdownText.value = `还有${hours}小时${minutes}分钟`
      } else if (minutes > 0) {
        countdownText.value = `还有${minutes}分钟${seconds}秒`
      } else {
        countdownText.value = `还有${seconds}秒`
      }
    }
    
    // 初始更新倒计时并设置定时器
    const setupCountdown = () => {
      updateCountdownText() // 初始更新
      
      // 每秒更新一次倒计时
      window.countdownTimer = setInterval(() => {
        updateCountdownText()
      }, 1000)
    }

    return {
      contestId,
      contestDetail,
      loading,
      comments,
      commentsLoading,
      commentContent,
      replyContent,
      showReplyForm,
      commentPage,
      commentPageSize,
      commentTotal,
      canJoinContest,
      isUserJoined,
      isLiveContestMode,
      canEnterLiveRoom,
      canEnterWaitingRoom,
      ArrowLeft,
      ThumbUp,
      
      fetchContestDetail,
      fetchComments,
      addComment: addNewComment,
      submitReply,
      likeComment: handleLikeComment,
      toggleReply,
      handleCommentSizeChange,
      handleCommentPageChange,
      handleJoin,
      goBack,
      viewRanking,
      getJoinButtonText,
      getStatusText,
      getStatusType,
      getStatusEffect,
      formatDateTime,
      enterLiveContest,
      rulesDialogVisible,
      remainingTime,
      countdownText,
      showRulesDialog,
      closeRulesDialog,
      isWithinTenMinutes
    }
  }
}
</script>

<style lang="scss" scoped>
.contest-detail-container {
  padding: 20px;
  
  .back-link {
    margin-bottom: 20px;
  }
  
  .loading-container {
    padding: 40px 0;
  }
  
  .not-found-container {
    padding: 60px 0;
    text-align: center;
  }
  
  .contest-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .detail-card {
    border-radius: 12px;
    overflow: hidden;
    
    .contest-header {
      margin-bottom: 20px;
      
      .title-status {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 10px;
        
        .contest-title {
          margin: 0;
          font-size: 24px;
          color: #2c3e50;
        }
        
        .contest-status {
          padding: 0 15px;
          height: 28px;
          line-height: 28px;
        }
      }
      
      .creator-info {
        color: #606266;
        font-size: 14px;
      }
    }
    
    .contest-cover {
      margin-bottom: 20px;
      height: 300px;
      border-radius: 8px;
      overflow: hidden;
      
      .cover-image {
        width: 100%;
        height: 100%;
      }
      
      .image-placeholder {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background-color: #f0f2f5;
        color: #909399;
      }
    }
    
    .contest-info {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 15px;
      margin-bottom: 20px;
      
      .info-item {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #606266;
        font-size: 14px;
        
        .el-icon {
          color: #409eff;
        }
      }
    }
    
    .contest-description {
      margin-bottom: 30px;
      
      h3 {
        margin-top: 0;
        margin-bottom: 15px;
        color: #2c3e50;
        font-size: 18px;
      }
      
      .description-content {
        color: #606266;
        line-height: 1.8;
        white-space: pre-line;
      }
    }
    
    .contest-actions {
      display: flex;
      justify-content: center;
      gap: 15px;
    }
  }
  
  .comment-card {
    border-radius: 12px;
    
    .comment-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h3 {
        margin: 0;
        color: #2c3e50;
      }
      
      span {
        color: #909399;
        font-size: 14px;
      }
    }
    
    .comment-input {
      margin-bottom: 20px;
      
      .input-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 10px;
      }
    }
    
    .comments-loading {
      padding: 20px 0;
    }
    
    .comments-empty {
      padding: 30px 0;
    }
    
    .comments-list {
      .comment-item {
        padding: 20px 0;
        border-bottom: 1px solid #ebeef5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .comment-user {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 10px;
          
          .user-info {
            .user-name {
              font-weight: 500;
              color: #2c3e50;
            }
            
            .comment-time {
              font-size: 12px;
              color: #909399;
              margin-top: 3px;
            }
          }
        }
        
        .comment-content {
          margin: 10px 0;
          color: #606266;
          line-height: 1.6;
        }
        
        .comment-actions {
          display: flex;
          gap: 15px;
          margin: 10px 0;
          
          .el-button {
            display: flex;
            align-items: center;
            gap: 5px;
          }
        }
        
        .reply-form {
          margin: 15px 0 15px 40px;
          
          .reply-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 10px;
          }
        }
        
        .replies-list {
          margin-left: 40px;
          margin-top: 15px;
          padding: 10px;
          background-color: #f8f9fa;
          border-radius: 8px;
          
          .reply-item {
            padding: 10px 0;
            border-bottom: 1px dashed #ebeef5;
            
            &:last-child {
              border-bottom: none;
            }
            
            .reply-user {
              display: flex;
              align-items: center;
              gap: 8px;
              
              .user-info {
                .user-name {
                  font-weight: 500;
                  color: #2c3e50;
                  font-size: 13px;
                }
                
                .reply-time {
                  font-size: 12px;
                  color: #909399;
                }
              }
            }
            
            .reply-content {
              margin: 5px 0 0 38px;
              color: #606266;
              font-size: 13px;
              line-height: 1.5;
            }
          }
        }
      }
    }
    
    .comment-pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }

  .rules-content {
    margin-bottom: 20px;
  }

  .countdown-timer {
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;
  }
}
</style> 